const app = getApp();
const db = wx.cloud.database()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    contactCur: [],
    page: 0,
  },

  onLoad: function (options) {
    wx.showLoading({
      title: '数据加载中...',
    })
    db.collection('contact').get().then(res => {
      this.setData({ contactCur: res.data })
    })
    wx.hideLoading()
  },

  bindKeyInput: function (event) {
    
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

  onReachBottom: function () {
    var page = this.data.page + 20
    db.collection('contact').skip(page).get().then(res => {
      console.log(res.data)
      var contactCur = this.data.contactCur
      contactCur = contactCur.concat(res.data)
      this.setData({ contactCur: contactCur, page: page })
    })
  },

  deleteperson: function (event) {
    var id = event.currentTarget.dataset.id
    var contactCur = this.data.contactCur
    var _id = contactCur[id]._id
    console.log(_id)
    contactCur.splice(id, 1)
    this.setData({ contactCur: contactCur})
    
    wx.cloud.callFunction({
      name: 'deleteperson',
      data: {
        _id: _id
      },
      success: function (res) {
        wx.showToast({
          title: '删除成功...',
          icon: 'none',
          duration: 1500
        })
      },
      fail: console.error
    })
  },
})